import { onActivated, onDeactivated, onBeforeUnmount, Ref, isRef } from 'vue'
import * as echarts from 'echarts'

/**
 * @description 使用Echarts(只是为了添加图表响应式)
 * @param {Element} ele Echarts实例或者Ref(必传)
 * @param {Object} options 绘制Echarts的参数(必传)
 * @return void
 * */
export const useEcharts = (ele: echarts.ECharts | Ref<HTMLElement | undefined>, options?: echarts.EChartsCoreOption) => {
	let chart: echarts.ECharts
	if (isRef(ele)) {
		chart = echarts.init(ele.value as HTMLElement)
	} else {
		chart = ele
	}
	if (options && typeof options === 'object') {
		chart.setOption(options)
	}
	const echartsResize = () => {
		chart && chart.resize()
	}

	window.addEventListener('resize', echartsResize)

	onActivated(() => {
		window.addEventListener('resize', echartsResize)
	})

	// 防止 echarts 页面 keepAlive 时，还在继续监听页面
	onDeactivated(() => {
		window.removeEventListener('resize', echartsResize)
	})

	onBeforeUnmount(() => {
		window.removeEventListener('resize', echartsResize)
	})

	return { chart }
}
